import { login } from '@/services/login';
import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormText,
} from '@ant-design/pro-components';
import { FormattedMessage, Helmet, SelectLang, useIntl, useModel } from '@umijs/max';
import { Alert, message } from 'antd';
import { createStyles } from 'antd-style';
import React, {useEffect, useState} from 'react';
import { flushSync } from 'react-dom';
import Settings from '../../../../config/defaultSettings';
import login_bg from '../../../assets/images/login_bg.png';
// import login_form_bg from '../../../assets/images/login_form_bg.png';
import login_form_bg from '../../../assets/images/login_form_bg.jpg';
import './index.less';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      // flexDirection: 'column',
      height: '100vh',
      // overflow: 'auto',
      // backgroundImage:
      //   "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundImage: `url(${login_bg})`,
      backgroundSize: '1184px 487px',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: '50%',
      backgroundColor: '#e8eeff'
    },
    login_form_container: {
      display: 'block',
      margin: '0 auto',
      width: '900px',
      height: '350px',
      padding: '0',
      backgroundImage: `url(${login_form_bg})`,
      backgroundSize: '536px 384px',
      backgroundRepeat: 'no-repeat',
      // backgroundSize: '425px 550px',
      backgroundPosition: '0 0',
      backgroundColor: '#fff',
      borderRadius: '50px !important',
      boxShadow: '0 2px 25px 0 rgba(0,0,0,.05)',
      position: 'relative',
    },
  };
});

const Lang = () => {
  const { styles } = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const intl = useIntl();

  useEffect(() => {
    // 在这里编写页面加载时要执行的逻辑
    localStorage.removeItem('auth')
    sessionStorage.removeItem('auth')
    console.log('login page loaded')
    // 如果有需要清理的操作，可以在这里返回一个函数
    return () => {
      // 清理操作
    };
  }, []); // 空数组表示这个effect只在组件挂载完成后运行一次

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async (values: LOGIN.LoginParams) => {
    try {
      // 登录
      const msg = await login({ ...values });
      if (msg.code !== 0) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        // localStorage.setItem('auth', JSON.stringify(msg.data))
        sessionStorage.setItem('auth', JSON.stringify(msg.data))
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        window.location.href = urlParams.get('redirect') || '/aud/list';
        return;
      }
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  const {code} = userLoginState;
  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          - {Settings.title}
        </title>
      </Helmet>
      <Lang />
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <div className={styles.login_form_container}>
        <LoginForm
          contentStyle={{
            minWidth: '280',
            maxWidth: '75vw',
            right: '0',
            top: '120px',
            width: '473px',
            height: '250px',
            position: 'absolute',
            textAlign: 'center',
            padding: '0 67px 0 60px',
            display: 'block',
            // border: '1px solid red',
          }}
          // logo={<img alt="logo" src="/logo.svg" />}
          title="您好"
          subTitle="欢迎登录"
          initialValues={{
            autoLogin: true,
          }}
          // actions={[
          //   <FormattedMessage
          //     key="loginWith"
          //     id="pages.login.loginWith"
          //     defaultMessage="其他登录方式"
          //   />,
          //   <ActionIcons key="icons" />,
          // ]}
          onFinish={async (values) => {
            await handleSubmit(values as LOGIN.LoginParams);
          }}
        >
          {/*<Tabs*/}
          {/*  activeKey={type}*/}
          {/*  onChange={setType}*/}
          {/*  centered*/}
          {/*  items={[*/}
          {/*    {*/}
          {/*      key: 'account',*/}
          {/*      label: intl.formatMessage({*/}
          {/*        id: 'pages.login.accountLogin.tab',*/}
          {/*        defaultMessage: '账户密码登录',*/}
          {/*      }),*/}
          {/*    },*/}
          {/*    {*/}
          {/*      key: 'mobile',*/}
          {/*      label: intl.formatMessage({*/}
          {/*        id: 'pages.login.phoneLogin.tab',*/}
          {/*        defaultMessage: '手机号登录',*/}
          {/*      }),*/}
          {/*    },*/}
          {/*  ]}*/}
          {/*/>*/}

          {code === 0 && code !== undefined  && (
            <LoginMessage
              content={intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: '账户或密码错误',
              })}
            />
          )}
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={ '用户名'}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
            </>

          <div
            style={{
              marginBottom: 24,
            }}
          >
            {/*<ProFormCheckbox noStyle name="autoLogin">*/}
            {/*  <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录" />*/}
            {/*</ProFormCheckbox>*/}
            <a
              style={{
                float: 'right',
              }}
            >

            </a>
          </div>
        </LoginForm>
        </div>
      </div>
      {/*<Footer />*/}
    </div>
  );
};

export default Login;
